import React, {Component} from 'react';
import 'whatwg-fetch';
import {Button, List, Toast} from 'antd-mobile';
import './style.scss';

const Item = List.Item;
const CryptoJS = require('crypto-js');
const Cookies = require('js-cookie');

const timeZone = -(new Date().getTimezoneOffset()/60)

export default class Daka extends Component {
  constructor(props) {
    super(props);
    const that = this;
    that.state = {
      'name': '', // 用户姓名
      'access_token': '', // access_token
      'token': '', // token
      'signInState': false, // 签到状态
      'signInText': '签到', // 签到文字
      'signOutState': false, // 签退状态
      'signOutText': '签退', // 签退文字
      'updateSignOutState': 'none', // 更新签退状态
    }
    that.cardInfo = that.cardInfo.bind(that);
    that.dakaClick = that.dakaClick.bind(that);
  }

  componentDidMount() {
    Cookies.set('PHPSESSID', '67fprbsq5mn11cloioo5tljh3l');
    Cookies.set('6336664de2c6419cbad95667501cf759', 'WyIyNDU2MzQ0MzYzIl0');
    const that = this;
    const {id} = that.props.match.params; // 获取工号
    // 获取access_token
    fetch('/daka/iSSC/wxapi/v2/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include'
    }).then((response) => {
      return response.json();
    }).then((data) => {
      if (data.access_token) {
        const access_token = data.access_token;
        that.setState({
          access_token
        });
        // 通过员工工号获取token
        fetch('/daka/iSSC/wxapi/v2/user', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + access_token,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            number: id,
            UserName: ''
          }),
          credentials: 'include'
        }).then((response) => {
          return response.json();
        }).then((res) => {
          if (res.ResultCode != 1000) {
            Toast.fail('获取用户信息失败，请输入正确的工号', 3);
          } else {
            const token = res.token;
            const name = res.name;
            that.setState({
              token,
              name
            });
            that.cardInfo(access_token, token);
          }
        }).catch((err) => {
          console.log('err', err);
        })
      } else {
        Toast.fail('获取access_token失败', 3);
      }
    }).catch((err) => {
      console.log('err', err);
    })
  }

  // 获取打卡状态信息
  cardInfo(access_token, token) {
    const that = this;
    // 通过token获取打卡信息
    fetch('/daka/iSSC/wxapi/v2/current', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + access_token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({token: token}),
      credentials: 'include'
    }).then((response) => {
      return response.json();
    }).then((result) => {
      const list = result.list;
      const qDList = [];
      const qTList = [];
      list && list.length > 0 && list.forEach((data) => {
        if (data.attenceType == 1 && data.attenceRemark == '签到' || data.attenceType == 2 || data.attenceType == 3) {
          qDList.push(data);
        } else if (data.attenceType == 1 && data.attenceRemark == '签退') {
          qTList.push(data);
        }
      })

      // 已经签到
      if (qDList.length > 0) {
        that.setState({
          signInState: true,
          signInText: `已签到 签到时间：${qDList[0].attenceClockTimeString}`
        });
      } else { // 没签到
        that.setState({
          signInState: false,
          signInText: '签到'
        });
      }

      // 已经签退
      if (qTList.length > 0) {
        that.setState({
          signOutState: true,
          signOutText: `已签退 签退时间：${qTList[qTList.length - 1].attenceClockTimeString}`,
          updateSignOutState: 'block'
        });
      } else { // 没签退
        that.setState({
          signOutState: false,
          signOutText: '签退',
          updateSignOutState: 'none'
        });
      }
    }).catch((err) => {
      console.log('err', err);
    })
  }

  // 签到或签退点击事件
  dakaClick(type) {
    const that = this;
    const name = that.state.name;
    const time = (new Date()).valueOf();
    const token = that.state.token;
    const access_token = that.state.access_token;
    if (name) {
      const postdata = {
        attencePointAddr: '郑州市中原区中国移动通信', // 位置
        attencePointLongitude: 113.548009, // 经度
        attencePointLatitude: 34.811917, // 纬度
        workPlaceLng: 113.546709,
        workPlaceLat: 34.810917,
        attencePointName: 'T&C郑州中移在线大厦',
        attenceDeviceID: time, // 打卡时间
        attenceType: 1,
        attenceRemark: type,
        token: Math.round(new Date().getTime()/1000).toString(),
        time_zone: timeZone
      };
      const data = JSON.stringify(postdata);
      const key = CryptoJS.enc.Utf8.parse('1a1a1a1b1e1c1s12');
      const iv =  CryptoJS.enc.Utf8.parse('1111111111111111');
      const encrypted = CryptoJS.AES.encrypt(data, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding });
      const msg = encrypted.toString();
      fetch('/newdaka/hwkq/api/v2/save-attence-record', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({"data":msg}),
        credentials: 'include'
      }).then((response) => {
        return response.json();
      }).then((res) => {
        if (res.ResultCode == 1000) {
          if (type == '签到') {
            that.setState({
              signInState: true,
              signInText: `已签到 签到时间：${res.attenceClockTimeString}`
            });
            Toast.success('签到成功', 1);
          } else if (type == '签退') {
            that.setState({
              signOutState: true,
              signOutText: `已签退 签退时间：${res.attenceClockTimeString}`,
              updateSignOutState: 'block'
            });
            Toast.success('签退成功', 1);
          }
        } else {
          Toast(res.ResultMessage, 1);
        }
      }).catch((err) => {
        console.log('err', err);
      });
    } else {
      Toast.fail('请先获取用户信息');
    }
  }

  render() {
    const that = this;
    return (
      <div className='daka'>
        {/*基本信息*/}
        <List className="daka-info">
          <Item
            className="daka-info-list"
            extra={that.state.name}
          >
            姓名
          </Item>
        </List>
        {/*签到按钮*/}
        <Button
          disabled={that.state.signInState}
          className="sign-in"
          type="primary"
          onClick={() => {
            that.dakaClick('签到');
          }}
        >
          {that.state.signInText}
        </Button>
        {/*签退按钮*/}
        <Button
          disabled={that.state.signOutState}
          className="sign-out"
          type="warning"
          onClick={() => {
            that.dakaClick('签退');
          }}
        >
          {that.state.signOutText}
        </Button>
        {/*更新签退按钮*/}
        <Button
          style={{'display': that.state.updateSignOutState}}
          className="sign-out-update"
          type="warning"
          onClick={() => {
            that.dakaClick('签退');
          }}
        >
          更新签退
        </Button>
      </div>
    );
  };
}